"use client"

import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { Player } from '@/types/player';
import { Badge } from '@/components/ui/badge';
import { updatePlayerTier } from '@/lib/data';
import { Medal, Save, RefreshCw, Search } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';

interface PlayerTiersManagerProps {
  selectedPlayerId: string | null;
  onSelectPlayer: (playerId: string | null) => void;
  players: Player[];
}

const GAME_MODES = [
  { id: 'SMP', name: 'SMP', field: 'smpTier' },
  { id: 'SWORD', name: '剑', field: 'swordTier' },
  { id: 'CRYSTAL', name: '水晶', field: 'crystalTier' },
  { id: 'BUHC', name: 'UHC', field: 'buhcTier' },
  { id: 'POTION', name: '药水', field: 'potionTier' },
  { id: 'NPOT', name: '合金pot', field: 'npotTier' },
];

const TIER_LEVELS = [
  { value: null, label: '无等级', tier: '', color: 'bg-gray-600' },
  { value: 1, label: 'HT1 (高阶一段)', tier: 'HT1', color: 'bg-yellow-500' },
  { value: 2, label: 'LT1 (低阶一段)', tier: 'LT1', color: 'bg-yellow-400' },
  { value: 3, label: 'HT2 (高阶二段)', tier: 'HT2', color: 'bg-orange-500' },
  { value: 4, label: 'LT2 (低阶二段)', tier: 'LT2', color: 'bg-orange-400' },
  { value: 5, label: 'HT3 (高阶三段)', tier: 'HT3', color: 'bg-blue-500' },
  { value: 6, label: 'LT3 (低阶三段)', tier: 'LT3', color: 'bg-blue-400' },
  { value: 7, label: 'HT4 (高阶四段)', tier: 'HT4', color: 'bg-green-500' },
  { value: 8, label: 'LT4 (低阶四段)', tier: 'LT4', color: 'bg-green-400' },
  { value: 9, label: 'HT5 (高阶五段)', tier: 'HT5', color: 'bg-gray-500' },
  { value: 10, label: 'LT5 (低阶五段)', tier: 'LT5', color: 'bg-gray-400' },
];

export default function PlayerTiersManager({ selectedPlayerId, onSelectPlayer, players }: PlayerTiersManagerProps) {
  const [selectedPlayer, setSelectedPlayer] = useState<Player | null>(null);
  const [tierValues, setTierValues] = useState<Record<string, number | null>>({});
  const [isLoading, setIsLoading] = useState(false);
  const [isSaving, setIsSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [success, setSuccess] = useState<string | null>(null);
  const [searchOpen, setSearchOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');

  // 数值段位到名称的映射函数
  const getTierNameFromValue = (value: number | null): string => {
    if (value === null) return '';
    const tier = TIER_LEVELS.find(t => t.value === value);
    return tier?.tier || '';
  };

  // 段位名称到数值的映射函数
  const getValueFromTierName = (tierName: string): number | null => {
    const tier = TIER_LEVELS.find(t => t.tier === tierName);
    return tier?.value ?? null; // 默认为null（无等级）
  };

  useEffect(() => {
    if (selectedPlayerId && players) {
      const player = players.find(p => p.id === selectedPlayerId);
      if (player) {
        setSelectedPlayer(player);
        
        // 初始化段位数据
        const initialTiers = {
          smpTier: player.smpTier ?? null,
          swordTier: player.swordTier ?? null,
          crystalTier: player.crystalTier ?? null,
          buhcTier: player.buhcTier ?? null,
          potionTier: player.potionTier ?? null,
          npotTier: player.npotTier ?? null,
        };
        
        setTierValues(initialTiers);
      }
    } else {
      setSelectedPlayer(null);
      setTierValues({});
    }
  }, [selectedPlayerId, players]);

  const handlePlayerChange = (playerId: string) => {
    onSelectPlayer(playerId);
    setSearchOpen(false);
  };

  const handleTierChange = (mode: string, value: string) => {
    const numValue = value === "null" ? null : parseInt(value);
    setTierValues(prev => ({
      ...prev,
      [mode]: numValue
    }));
  };

  const handleSaveTiers = async () => {
    if (!selectedPlayer) return;
    
    setIsSaving(true);
    setError(null);
    setSuccess(null);
    
    try {
      await updatePlayerTier(selectedPlayer.id, tierValues);
      setSuccess('玩家段位更新成功');
      
      // 3秒后自动清除成功提示
      setTimeout(() => {
        setSuccess(null);
      }, 3000);
    } catch (err: any) {
      console.error('更新段位失败:', err);
      setError(err.message || '更新段位失败，请稍后重试');
    } finally {
      setIsSaving(false);
    }
  };

  const renderTierBadge = (tier: number | null) => {
    const tierInfo = TIER_LEVELS.find(t => t.value === tier);
    return (
      <Badge className={`${tierInfo?.color || 'bg-gray-600'} text-white`}>
        {tierInfo?.tier || '无等级'}
      </Badge>
    );
  };

  // 过滤玩家列表函数
  const filteredPlayers = searchQuery.trim() === ''
    ? players 
    : players.filter(player => {
      // 确保player.name存在且是字符串
      const playerName = (player.name || '').toString().toLowerCase();
      // 确保player.id存在且转为字符串
      const playerId = (player.id || '').toString();
      // 搜索字符串转小写
      const query = searchQuery.toLowerCase().trim();
            
      // 检查名称或ID是否包含搜索字符串
      return playerName.includes(query) || playerId.includes(query);
    });

  // 调试信息
  console.log('搜索查询:', searchQuery);
  console.log('过滤后玩家数:', filteredPlayers.length);
  console.log('总玩家数:', players.length);

  return (
    <Card className="border border-gray-800 bg-[#1a1d24]">
      <CardHeader>
        <CardTitle>玩家段位管理</CardTitle>
        <CardDescription>管理玩家在各游戏模式下的段位</CardDescription>
      </CardHeader>
      <CardContent>
        <div className="space-y-6">
          <div className="flex flex-col space-y-2">
            <label className="text-sm font-medium text-gray-300">选择玩家</label>
            
            {/* 新的玩家选择器，带搜索功能 */}
            <Popover open={searchOpen} onOpenChange={setSearchOpen}>
              <PopoverTrigger asChild>
                <Button 
                  variant="outline" 
                  role="combobox" 
                  aria-expanded={searchOpen}
                  className="w-full justify-between bg-[#252a33] border-gray-700 text-left font-normal"
                >
                  {selectedPlayer ? selectedPlayer.name : "选择玩家..."}
                  <Search className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-full p-0 bg-[#2a2e35] border-gray-700">
                <Command className="bg-transparent">
                  <div className="flex items-center px-3 border-b border-gray-700">
                    <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
                    <input
                      className="flex h-9 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-gray-500 disabled:cursor-not-allowed disabled:opacity-50"
                      placeholder="搜索玩家..."
                      value={searchQuery}
                      onChange={(e) => setSearchQuery(e.target.value)}
                    />
                    {searchQuery && (
                      <Button
                        variant="ghost"
                        size="sm"
                        onClick={() => setSearchQuery('')}
                        className="h-5 w-5 p-0 rounded-full"
                      >
                        <span>×</span>
                      </Button>
                    )}
                  </div>
                  <CommandList>
                    <CommandEmpty>未找到玩家</CommandEmpty>
                    <CommandGroup>
                      <ScrollArea className="h-[200px]">
                        {filteredPlayers.length > 0 ? (
                          filteredPlayers.map((player) => (
                            <CommandItem
                              key={player.id}
                              value={player.id}
                              onSelect={() => handlePlayerChange(player.id)}
                              className="cursor-pointer hover:bg-gray-700"
                            >
                              <div className="flex items-center gap-2">
                                <div className="w-6 h-6 rounded-full overflow-hidden flex-shrink-0">
                                  <img 
                                    src={player.avatar || "/placeholder-user.jpg"} 
                                    alt="" 
                                    className="h-full w-full object-cover"
                                    onError={(e) => { (e.target as HTMLImageElement).src = '/placeholder-user.jpg' }}
                                  />
                                </div>
                                <span>{player.name}</span>
                                <span className="text-xs text-gray-400">ID: {player.id}</span>
                              </div>
                              {player.id === selectedPlayerId && (
                                <span className="ml-auto">✓</span>
                              )}
                            </CommandItem>
                          ))
                        ) : (
                          <div className="py-6 text-center text-sm text-gray-500">
                            加载中...
                          </div>
                        )}
                      </ScrollArea>
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>
          </div>

          {error && (
            <div className="bg-red-500/20 border border-red-500 text-red-300 p-3 rounded">
              {error}
            </div>
          )}

          {success && (
            <div className="bg-green-500/20 border border-green-500 text-green-300 p-3 rounded">
              {success}
            </div>
          )}

          {selectedPlayer ? (
            <div className="space-y-6">
              <div className="flex items-center space-x-4">
                <div className="w-12 h-12 overflow-hidden rounded-full">
                  <img 
                    src={selectedPlayer.avatar || '/default-avatar.jpg'} 
                    alt={selectedPlayer.name}
                    className="w-full h-full object-cover"
                    onError={(e) => { (e.target as HTMLImageElement).src = '/default-avatar.jpg' }}
                  />
                </div>
                <div>
                  <h3 className="text-lg font-semibold">{selectedPlayer.name}</h3>
                  <p className="text-sm text-gray-400">
                    {selectedPlayer.region || '未知地区'} · ID: {selectedPlayer.id}
                  </p>
                </div>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {GAME_MODES.map(mode => (
                  <div key={mode.id} className="border border-gray-700 rounded-lg p-4">
                    <div className="flex justify-between items-center mb-3">
                      <h4 className="font-medium flex items-center">
                        <Medal className="h-4 w-4 mr-2" />
                        {mode.name}
                      </h4>
                      {renderTierBadge(tierValues[mode.field])}
                    </div>
                    
                    <Select
                      value={(tierValues[mode.field] === null ? "null" : tierValues[mode.field]?.toString()) || ''}
                      onValueChange={(value) => handleTierChange(mode.field, value)}
                      disabled={isSaving}
                    >
                      <SelectTrigger className="w-full bg-[#252a33] border-gray-700">
                        <SelectValue placeholder="选择段位" />
                      </SelectTrigger>
                      <SelectContent className="bg-[#2a2e35] border-gray-700 text-white">
                        {TIER_LEVELS.map(tier => (
                          <SelectItem key={tier.value} value={tier.value === null ? "null" : tier.value.toString()} className="focus:bg-gray-700">
                            {tier.label}
                          </SelectItem>
                        ))}
                      </SelectContent>
                    </Select>
                  </div>
                ))}
              </div>

              <div className="flex justify-end space-x-3">
                <Button 
                  variant="outline" 
                  onClick={() => {
                    if (selectedPlayer) {
                      const initialTiers = {
                        smpTier: selectedPlayer.smpTier ?? null,
                        swordTier: selectedPlayer.swordTier ?? null,
                        crystalTier: selectedPlayer.crystalTier ?? null,
                        buhcTier: selectedPlayer.buhcTier ?? null,
                        potionTier: selectedPlayer.potionTier ?? null,
                        npotTier: selectedPlayer.npotTier ?? null,
                      };
                      setTierValues(initialTiers);
                    }
                  }}
                  disabled={isSaving}
                  className="border-gray-700"
                >
                  <RefreshCw className="h-4 w-4 mr-2" />
                  重置
                </Button>
                <Button 
                  onClick={handleSaveTiers}
                  disabled={isSaving}
                  className="bg-blue-600 hover:bg-blue-700"
                >
                  {isSaving ? (
                    <>
                      <span className="animate-spin h-4 w-4 mr-2 border-2 border-white border-t-transparent rounded-full"></span>
                      保存中...
                    </>
                  ) : (
                    <>
                      <Save className="h-4 w-4 mr-2" />
                      保存段位
                    </>
                  )}
                </Button>
              </div>
            </div>
          ) : isLoading ? (
            <div className="space-y-4">
              <Skeleton className="h-12 w-full" />
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                {[1, 2, 3, 4, 5, 6].map(i => (
                  <Skeleton key={i} className="h-24 w-full" />
                ))}
              </div>
            </div>
          ) : (
            <div className="text-center py-8 text-gray-500">
              请选择一个玩家进行段位管理
            </div>
          )}
        </div>
      </CardContent>
    </Card>
  );
} 